package com.itany.corejava.code12_线程;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年11月29日 16:37
 */
public class Test12_练习 {
    public static boolean flag=true;
    public static int count=10;
    public static void main(String[] args) {
        Object object=new Object();
        A a=new A(object);
        B b=new B(object);
        a.start();
        b.start();

    }
}
// 定义两个线程类，一个线程输出A、一个线程输出B，交替输出10次
// 控制台：ABABAB.....
class A extends Thread{
    private Object o;

    public A(Object o) {
        this.o = o;
    }

    @Override
    public void run() {
        while(true){
           synchronized (o){
               if(Test12_练习.flag){
                   System.out.println("A");
                   Test12_练习.flag=false;
                   o.notifyAll();
                   if(Test12_练习.count==1){
                       break;
                   }
                   try {
                       o.wait();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }

               }
           }
        }
    }
}
class B extends  Thread{
    private Object o;

    public B(Object o) {
        this.o = o;
    }
    @Override
    public void run() {
        while(true){
            synchronized (o){
                if(!Test12_练习.flag){
                    System.out.println("B");
                    if(Test12_练习.count==1){
                        break;
                    }
                    Test12_练习.count--;
                    Test12_练习.flag=true;
                    o.notifyAll();
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }
}